/**
 * XLSParser.java
 * @authors: Connor Gordon, Difan Zhao, Kathleen Lan, Patrick Royal
 */

package io;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import model.Element;
import model.StockElement;


/**
 * 
 * @author Group 8
 * 
 */
public class XLSParser extends DataParser {

    private static final String EXT = ".xls";
    //private String urlString;

    /**
     * Constructor for XLSParser given file.
     * 
     * @param name name of the data set
     * @param id id of the data set
     * @param f file to read
     */
    public XLSParser (String name, String id, File f) {
        super(name, id, f);
    }

    /**
     * Constructor for XLSParser given url.
     * 
     * @param name name of the data set
     * @param id of the data set
     * @param url source of the data
     */
    public XLSParser (String name, String id, String url) {
        super(name, id, url, EXT);
        //urlString = url;
    }

    @Override
    public Element parseData () {
        Workbook w;
        Map<String, List<Double>> data = new HashMap<String, List<Double>>();

        try {
            w = Workbook.getWorkbook(getFile());
            System.out.println(w.getNumberOfSheets());
            Sheet sheet = w.getSheet(0);
            Map<Integer, String> posToIndex = new HashMap<Integer, String>();
            for (int i = 1; i < sheet.getRows(); i++) { 
                for (int j = 1; j < sheet.getColumns(); j++) {
                    Cell cell = sheet.getCell(i, j);
                    String contents = cell.toString();
                    if (i == 0) {
                        data.put(contents, new LinkedList<Double>());
                        posToIndex.put(j, contents);
                    }
                    else {
                        data.get(posToIndex.get(j)).add(Double.parseDouble(cell.toString()));
                    }

                }
            }
        }
        catch (IOException e) {
            System.out.println("Unable to read .xls file");
        }
        catch (BiffException e) {
            e.printStackTrace();
        }
        if (getFile().getName().contains("loadin")) {
            getFile().delete();
        }
        return new StockElement(getName(), getId(), Collections.unmodifiableMap(data));
    }

}
